package com.pojocreator.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pojocreator.common.AccessProperties;

public class ConnectionManager {
	private static final Log log = LogFactory.getLog(ConnectionManager.class);
	
	private Connection connection;
	private String userName;
	private String passWord;
	private String url;
	
	public ConnectionManager(){
		this.connection=null;
		this.url=null;
		this.userName=null;
		this.passWord=null;
	}
	public ConnectionManager(String url,String userName,String passWord){
		this.url=url;
		this.userName=userName;
		this.passWord=passWord;
		try {
			Class.forName(AccessProperties.getValueFromProps("db.DriverClassName"));
			log.debug("JDBC Driver Registered!");
		} catch (ClassNotFoundException e) {
			log.info("Where is your JDBC Driver?");
			log.error("",e);
			this.connection=null;
		}
		try {
			this.connection = DriverManager.getConnection(url,userName,passWord);
		} catch (SQLException e) {
			log.info("Connection Failed!:"+e.getMessage());
			/*log.info(e.getErrorCode());
			log.info(e.toString());*/
			log.error("",e);
			return;
		}
		if (this.connection != null) {
			log.info("Successfully Connected to Database");
		} else {
			log.info("Failed to make connection!");
		}
	}
	public Connection getConnection() {
		return connection;
	}
	public void setConnection(Connection connection) {
		this.connection = connection;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassWord() {
		return passWord;
	}
	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	
	public void closeConnection() throws SQLException{
		if (this.connection != null) {
			this.connection.close();
			log.info("Successfully closed connection");
		}
	}
}
